<template>
  <el-drawer
      v-model="showFlag"
      append-to-body
      :before-close="cancel">
    <div style="margin: 20px">
      <el-form :model="refForm" :rules="rules" ref="formView"  label-position="top" size="default">
        <el-form-item label="组织归属" prop="deptId">
          <el-tree-select node-key="deptId" v-model="refForm.deptId" :props="{label: 'deptName',children: 'children'}"
                          :data="deptTree" check-strictly/>
        </el-form-item>

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="refForm.userName"/>
        </el-form-item>


        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="refForm.nickName"/>
        </el-form-item>

        <el-form-item label="联系电话" prop="phonenumber">
          <el-input v-model="refForm.phonenumber"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="refForm.email"/>
        </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="refForm.sex">
                  <el-radio v-for="item in sexOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="状态" prop="state">
                <el-radio-group v-model="refForm.state">
                  <el-radio v-for="item in stateOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
           <el-form-item label="角色" class="mt10" prop="roleIds" >
             <el-select multiple v-model="refForm.roleIds" placeholder="请选择状态" style="width:100%" ref="roleSelectRef" @change="roleSelectChange">
               <el-option
                   v-for="item in roleOptions"
                   :label="item.roleName"
                   :value="item.roleId"
               />
             </el-select>
           </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea" v-model="refForm.remark"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div style="text-align: center;margin-bottom: 10px">
        <el-button size="default" @click="cancel()">取消</el-button>
        <el-button size="default" type="primary" @click="subimt()" v-auths="['system-user-update', 'system-user-add']">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {queryAll} from "/@/api/system/role";
import {addUser,updateUser} from "/@/api/system/user";
import { isvalidPhone, validEmail } from '/@/utils/validate'
import {ElMessage} from "element-plus";
const props = defineProps({
  deptTree: {
    type: Array,
    required: true
  },
  stateOptions: {
    type: Array,
    required: true
  }
})
const emits = defineEmits(['ok'])
const {proxy} = getCurrentInstance()
const showFlag = ref(false)
const formView = ref()
const roleSelectRef = ref()
// 自定义验证
const validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!isvalidPhone(value)) { //判断用户输入的值是否符合规则
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

// 自定义验证
const checkdEmail = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入邮箱地址'))
  } else if (!validEmail(value)) { //判断用户输入的值是否符合规则
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}
const rules = reactive({
  deptId:[{required: true, message: '请选择归属组织', trigger: 'blur'}],
  userName:[{required: true, message: '请输入用户名', trigger: 'blur'}],
  nickName:[{required: true, message: '请输入昵称', trigger: 'blur'}],
  email:[{required: true,validator: checkdEmail, trigger: 'blur'}],
  phonenumber:[{required: true,validator: validPhone, trigger: 'blur'}],
  sex:[{required: true, message: '请选择用户性别', trigger: 'blur'}],
  state:[{required: true, message: '请选择状态', trigger: 'blur'}],
})
const refForm = reactive({
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  email: undefined,
  phonenumber: undefined,
  sex: '0',
  state: '0',
  roleIds: [],
  remark: undefined
})
const  backForm =reactive({})
const open = (node) => {
  if (node) {
    Object.assign(refForm, JSON.parse(JSON.stringify(node)))
  }

  showFlag.value = true
}
const cancel = () => {
  formView.value.clearValidate()
  formView.value.resetFields()
  Object.assign(refForm, backForm)
  showFlag.value = false
}
const subimt = async () => {
  await proxy.$refs.formView.validate((valid) => {
    if (valid) {
      refForm.createTime=null
      if (!refForm.userId) {
        addUser(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      } else {
        updateUser(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      }
    }
  })
}

const roleSelectChange =()=>{
  roleSelectRef.value.blur()
}

defineExpose({
  open
})
const sexOptions = ref([])
const roleOptions = ref([])
onBeforeMount(() => {
  Object.assign(backForm, refForm)
  proxy.$dictOptions('sys_user_sex').then(res => {
    const {data} = res
    sexOptions.value = data
  })
  queryAll().then(res => {
    const {data} = res
    roleOptions.value = data
  })
})
</script>

<style scoped>
</style>